package com.vcc.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vcc.core.exception.NotFoundException;
import com.vcc.data.entity.IpInfo;
import com.vcc.data.mapper.IpInfoMapper;
import com.vcc.service.service.IpInfoService;
import org.springframework.stereotype.Service;

@Service
public class IpInfoServiceImpl extends ServiceImpl<IpInfoMapper,IpInfo> implements IpInfoService {
    @Override
    public IpInfo getByIp(String ip) {
        return queryChain().eq(IpInfo::getIp,ip).oneOpt().orElseThrow(()-> new NotFoundException("没有当前IP记录"));
    }

    @Override
    public IpInfo getByIpOrNull(String ip) {
        return queryChain().eq(IpInfo::getIp,ip).oneOpt().orElse(null);
    }

    @Override
    public Boolean existsByIp(String ip) {
        return queryChain().eq(IpInfo::getIp,ip).exists();
    }

    @Override
    public IpInfo save(JSONObject map) {
         try {
             return getByIp(map.getString("ip"));
        } catch (NotFoundException e) {
            IpInfo ipInfo = new IpInfo();
            ipInfo.setArea(map.getString("area"));
            ipInfo.setCountry(map.getString("country"));
            ipInfo.setLongIp(map.getString("long_ip"));
            ipInfo.setCity(map.getString("city"));
            ipInfo.setIp(map.getString("ip"));
            ipInfo.setIsp(map.getString("isp"));
            ipInfo.setDistrict(map.getString("district"));
            ipInfo.setRegionId(map.getString("region_id"));
            ipInfo.setDistrictId(map.getString("district_id"));
            ipInfo.setRegion(map.getString("region"));
            ipInfo.setCountryId(map.getString("country_id"));
            ipInfo.setCityId(map.getString("city_id"));
            save(ipInfo);
            return ipInfo;
        }
    }
}
